"""
认证服务
"""
from flask_login import login_user, logout_user, login_required
from werkzeug.security import generate_password_hash, check_password_hash
from app.models import User, get_db

class AuthService:
    """认证服务类"""
    
    @staticmethod
    def login(username, password):
        """用户登录"""
        db = get_db()
        user = User.query.filter_by(username=username).first()
        
        if user and user.check_password(password):
            login_user(user)
            return True, "登录成功"
        
        return False, "用户名或密码错误"
    
    @staticmethod
    def logout():
        """用户登出"""
        logout_user()
        return True, "登出成功"
    
    @staticmethod
    def register(username, email, password, role='user'):
        """用户注册"""
        db = get_db()
        
        # 检查用户名是否已存在
        if User.query.filter_by(username=username).first():
            return False, "用户名已存在"
        
        # 检查邮箱是否已存在
        if User.query.filter_by(email=email).first():
            return False, "邮箱已被注册"
        
        # 创建新用户
        user = User(
            username=username,
            email=email,
            role=role
        )
        user.set_password(password)
        
        db.session.add(user)
        db.session.commit()
        
        return True, "注册成功"